package com.bdqn.tsyyds.service.Student;

import com.bdqn.tsyyds.entity.Student;
import com.bdqn.tsyyds.repository.StudentRepostiory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StudentServicelmp implements StudentService {
    @Resource
    StudentRepostiory studentRepostiory;

    @Override
    public Student findByStdNameAndPassword(String stdName, String password) {
        return studentRepostiory.findByStdNameAndPassword(stdName, password);
    }

    @Override
    public Student findByUserNameBiz(String usrName) {
        return studentRepostiory.findByStdName(usrName);
    }

    @Override
    public Page<Student> findPageByMap(Map param, Pageable pageable) {
        System.out.println("findPageByMap" + "\t" + "stdName" + param.get("stdName") + "permissionId" + param.get("permissionId"));
        return studentRepostiory.findAll(new Specification<Student>() {
            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("stdName") != null && !param.get("stdName").equals("")) {
                    predicates.add(cb.like(root.get("stdName"), "%" + param.get("stdName") + "%"));
                }
                System.out.println(param.get("permissionId").toString().equals("0"));
                if (param.get("permissionId") != null && !param.get("permissionId").toString().equals("0")) {
                    predicates.add(cb.equal(root.get("permission"), param.get("permissionId")));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
                // where usrName like '%usrName%'
            }
        }, pageable);
    }

    @Override
    public Student findSave(Student student) {
        return studentRepostiory.save(student);
    }

    @Override
    public Student select(Long id) {
        return studentRepostiory.findAllById(id);
    }

    @Override
    public void delel(Long id) throws Exception {
        studentRepostiory.deleteById(id);

    }
}
